package com.intel.bluetooth;

import com.medlinx.vstp.VstpCommandBit;
import com.medlinx.vstp.VstpEcgDataPacketPayload;
import com.medlinx.vstp.VstpFramer;
import com.medlinx.vstp.VstpPacket;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class ProcessVstp {

	private static final int VSTPBUF_SIZE = 102400;
	public static int frequency = 300;

	private static ProcessVstp instance;

	private VstpPacket pkt = null;
	private ByteBuffer vstpBuf = ByteBuffer.allocate(VSTPBUF_SIZE);
	private VstpFramer framer = new VstpFramer();

	private MultiChannelBufferBT dbi;
	private List<Boolean> leadIsLink = new ArrayList<Boolean>();

	private int patientID;
	private boolean bindDeviceOk;

	// 上次保存心率时间
	long preSaveTime = 0;

	public static ProcessVstp getInstance() {
		if (instance == null)
			synchronized (ProcessVstp.class) {
				if (instance == null) {
					instance = new ProcessVstp();
				}
			}

		return instance;
	}

	public ProcessVstp() {
		for (int i = 0; i < 10; i++) {
			leadIsLink.add(false);
		}
		dbi = new MultiChannelBufferBT();

	}

	public void setDbi(MultiChannelBufferBT dbi) {
		this.dbi = dbi;
	}

	public List<Boolean> getLeadIsLink() {
		return leadIsLink;
	}

	public void setLeadIsLink(List<Boolean> leadIsLink) {
		this.leadIsLink = leadIsLink;
	}

	public int getPatientID() {
		return patientID;
	}

	public MultiChannelBufferBT getDbi() {
		return dbi;
	}

	public void setBindDeviceOk(boolean bindDeviceOk) {
		this.bindDeviceOk = bindDeviceOk;
	}

	public void setPatientID(int patientID) {
		this.patientID = patientID;
	}

	public boolean parseVstpPacket(byte[] buffer, int len) throws Exception {
		vstpBuf.put(buffer, 0, len);
		vstpBuf.flip();
		ByteBuffer frame = framer.decode(vstpBuf);
		vstpBuf.compact();
		if (frame != null) {
			frame.flip();
			pkt = new VstpPacket();
			pkt.decode(frame);

			if (dbi != null)
				dbi.setDataType(pkt.getDataType());
			if (pkt.getCommandBit().equals(VstpCommandBit.COMMAND)) {

			} else if (pkt.getCommandBit().equals(VstpCommandBit.DATA)) {
				readVstpDataPacket(pkt);
			}
		}
		return bindDeviceOk;
	}

	public void readVstpDataPacket(VstpPacket pkt) {
		VstpEcgDataPacketPayload payload = (VstpEcgDataPacketPayload) pkt
				.getPayload();
		int[][] buffer = payload.getECGDataBuffer();

		if (dbi != null) {
			dbi.putECGDataBuffer(buffer);
		}

	}

}
